<template>
  <app-card>
    <template #header>
      <el-space :size="10" spacer="|">
        <el-button
            type="primary"
            @click="uploadMedia"
        >
          <el-icon>
            <uploadFilled/>
          </el-icon>
          上传视频
        </el-button>
        <el-button
            type="info"
            @click="allSelect"
        >
          <el-icon>
            <Select/>
          </el-icon>
          全选
        </el-button>
        <el-button
            type="danger"
            @click="batchDelete"
        >
          <el-icon>
            <delete/>
          </el-icon>
          删除视频
        </el-button>
        <el-button
            type="success"
            @click="loadList"
        >
          <el-icon>
            <refresh/>
          </el-icon>
          刷新视频
        </el-button>
      </el-space>
    </template>
    <div class="videoList" v-resize:30="resize" v-loading="listLoading">
      <item :key="item.id" :item-width="itemWidth" v-model:show="item.show" v-model:checkedFlag="item.checked"
            :image-path="item.image"
            v-for="(item) in list">
        <span class="title">上传时间：{{ item.createdAt }}</span>
        <span class="name">
          视频：{{ bytesToSize(item.fileSize) }}
        </span>
        <div class="control">
          <p>
            <span>&nbsp;MP4 &nbsp;</span>
            <span @click.stop="playOpen(item.mp4Path,item.fileName)">播放视频</span>
            <span @click.stop="copyUrl(item.mp4Path)">拷贝地址</span>
          </p>
          <p  v-if="item.m3u8Path!==''">
            <span>M3U8</span>
            <span @click.stop="playOpen(item.m3u8Path,item.fileName)">播放视频</span>
            <span @click.stop="copyUrl(item.m3u8Path)">拷贝地址</span>
          </p>
        </div>
      </item>
    </div>
    <app-pagination
        v-model:page="listParams.pageNum"
        v-model:limit="listParams.pageSize"
        :list-count="listCount"
        :load-list="loadList"
        :disabled="listLoading"
    />
    <video-play ref="play" v-model="playVisible">

    </video-play>
  </app-card>

</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue';
import {getVideoList} from '@/api/static';
import {VideoInfo} from "@/api/types/static";
import {IListParams} from "@/api/types/common";
import {bytesToSize, copy} from "@/utils/constants";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import Item from '../component/Item.vue'
import VideoPlay from '../component/VideoPlay.vue'
import {delFile, FileResp, upload} from "@/api/upload"

const play = ref<any>();
const list = ref<VideoInfo[]>([]);
const listCount = ref(0);
const listLoading = ref(false);
const playVisible = ref(false);
const listParams = reactive<IListParams>({
  pageNum: 1,
  pageSize: 20,
});

onMounted(() => {
  loadList();
});

const loadList = async () => {
  listLoading.value = true;
  const data = await getVideoList(listParams).finally(() => {
    listLoading.value = false;
  });
  list.value = data.rows;
  listCount.value = data.total;
};

const playOpen = (path: string, name: string) => {
  play.value.playVideo(path, name)
  playVisible.value = true
}

const copyUrl = (path: string) => {
  copy(path)
  ElMessage.success(`地址【${path}】已拷贝!`)
}

// 上传视频
const uploadMedia = () => {
  const input = document.createElement('input') as HTMLInputElement
  input.setAttribute('type', 'file')
  input.setAttribute('accept', '.mp4')
  input.click()
  input.onchange = () => {
    const loading = ElLoading.service({
      lock: true,
      text: `正在上传 【1%】`,
      background: 'rgba(0, 0, 0, 0.7)',
    })
    upload('media', input.files![0], {m3u8: '1'},(progress: any) => {
      // 设置内容
      loading.setText("正在上传 【"+ Math.round(progress.loaded / progress.total * 100) + '%】')
    }).then((resp: FileResp) => {
      loading.close()
      ElMessage.success(`上传成功!`)
      loadList()
    })
  }
}

// 批量删除视频
const batchDelete = () => {
  const delList = list.value.filter((i) => {
    return i.checked
  }).map((i) => {
    return i.mp4Path
  })
  if (delList.length === 0) {
    ElMessage.warning(`请选择要删除的视频文件!`)
    return
  }
  ElMessageBox.confirm(
      '是否永久删除选择的视频！',
      '提醒', {confirmButtonText: '确认', cancelButtonText: '取消',})
      .then(async () => {
        for (const path of delList) {
          await delFile('media', path)
        }
        ElMessage.success(`视频已删除!`)
        await loadList()
      })
}

// 全选
const allSelect = () => {
  const flag = list.value[0]?.checked
  list.value.forEach((i) => {
    i.checked = !flag
  })
}

// 宽度自适应
const itemWidth = ref('250px')
const resize = (el: HTMLElement) => {
  const i = Math.floor(el.clientWidth / 250)
  if (i) {
    itemWidth.value = Math.floor(el.clientWidth / i) - 10 + 'px'
  }
}

</script>

<style lang="scss" scoped>

div.videoList {
  display: flex;
  justify-content: flex-start;
  align-content: center;
  flex-wrap: wrap;

  span {
    padding-left: 5px;
  }

  span.title {
    line-height: 30px;
  }

  span.name {
    line-height: 15px;
  }

  div.control {
    margin-top: 5px;

    & > p {
      padding: 2px;
      background: #1c6ca1;
      border-radius: 5px;
      color: #ffffff;
      margin: 2px;
      font-size: 13px;

      & > span:nth-child(1) {
        font-weight: bold;
        color: #00feff;
      }

      & > span:nth-child(2):hover {
        color: #ce9da8;
      }

      & > span:nth-child(3):hover {
        color: #b1b4d3;
      }
    }
  }
}

</style>
